<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { ElButton, ElProgress, ElTable, ElTableColumn, ElTag, ElIcon, ElDropdown, ElDropdownMenu, ElDropdownItem, ElSlider } from 'element-plus';
import { useDownloadStore, DownloadStatus } from '../../store/download';
import IconPause from '../../assets/svg/player/icon-player-pause.svg';
import IconPlay from '../../assets/svg/icon-loading-play.svg';
import IconDelete from '../../assets/svg/icon-delete.svg';
import IconRedo from '../../assets/svg/icon-redo.svg';
import IconMore from '../../assets/svg/icon-more.svg';

const downloadStore = useDownloadStore();
const { tasks, maxConcurrentTasks } = downloadStore;

// 初始化下载管理器
onMounted(() => {
  downloadStore.initialize();
});

// 过滤任务
const filterType = ref<string>('all');
const filteredTasks = computed(() => {
  switch (filterType.value) {
    case 'all':
      return tasks;
    case 'waiting':
      return tasks.filter(task => task.status === DownloadStatus.WAITING);
    case 'downloading':
      return tasks.filter(task => task.status === DownloadStatus.DOWNLOADING);
    case 'completed':
      return tasks.filter(task => task.status === DownloadStatus.COMPLETED);
    case 'failed':
      return tasks.filter(task => task.status === DownloadStatus.FAILED);
    case 'paused':
      return tasks.filter(task => task.status === DownloadStatus.PAUSED);
    default:
      return tasks;
  }
});

// 任务状态文本和标签类型
const getStatusInfo = (status: DownloadStatus) => {
  switch (status) {
    case DownloadStatus.WAITING:
      return { text: '等待中', type: 'info' };
    case DownloadStatus.DOWNLOADING:
      return { text: '下载中', type: 'primary' };
    case DownloadStatus.COMPLETED:
      return { text: '已完成', type: 'success' };
    case DownloadStatus.FAILED:
      return { text: '失败', type: 'danger' };
    case DownloadStatus.PAUSED:
      return { text: '已暂停', type: 'warning' };
    default:
      return { text: '未知', type: 'info' };
  }
};

// 获取过滤器文本
const getFilterText = (filter: string) => {
  const filterMap: Record<string, string> = {
    'all': '全部',
    'waiting': '等待中',
    'downloading': '下载中',
    'completed': '已完成',
    'failed': '失败',
    'paused': '已暂停'
  };
  return filterMap[filter] || '全部';
};

// 格式化时间
const formatTime = (timestamp: number | undefined) => {
  if (!timestamp) return '-';
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

// 格式化时长
const formatDuration = (startTime: number | undefined, endTime: number | undefined) => {
  if (!startTime) return '-';
  const end = endTime || Date.now();
  const duration = (end - startTime) / 1000;
  
  if (duration < 60) {
    return `${Math.floor(duration)}秒`;
  } else if (duration < 3600) {
    const minutes = Math.floor(duration / 60);
    const seconds = Math.floor(duration % 60);
    return `${minutes}分${seconds}秒`;
  } else {
    const hours = Math.floor(duration / 3600);
    const minutes = Math.floor((duration % 3600) / 60);
    return `${hours}时${minutes}分`;
  }
};

// 暂停下载
const pauseTask = (taskId: string) => {
  downloadStore.pauseDownloadTask(taskId);
};

// 开始下载
const startTask = (taskId: string) => {
  downloadStore.startDownloadTask(taskId);
};

// 取消下载
const cancelTask = (taskId: string) => {
  downloadStore.cancelDownloadTask(taskId);
};

// 重试下载
const retryTask = (taskId: string) => {
  downloadStore.startDownloadTask(taskId);
};

// 清空已完成任务
const clearCompletedTasks = () => {
  // 实际实现中可以添加确认对话框
  const taskIds = tasks.filter(task => task.status === DownloadStatus.COMPLETED).map(task => task.id);
  taskIds.forEach(id => {
    const taskIndex = tasks.findIndex(t => t.id === id);
    if (taskIndex !== -1) {
      tasks.splice(taskIndex, 1);
    }
  });
};

// 清空全部任务
const clearAllTasks = () => {
  // 实际实现中可以添加确认对话框
  downloadStore.tasks = [];
  downloadStore.runningTasks = 0;
};
</script>

<template>
  <div class="download-tasks">
    <div class="header">
      <h3>下载任务</h3>
      <div class="header-actions">
        <div class="concurrent-control" style="display: flex; align-items: center; margin-right: 20px;">
          <span style="font-size: 12px; margin-right: 8px;">并发任务:</span>
          <ElSlider 
            v-model="downloadStore.maxConcurrentTasks" 
            :min="1" 
            :max="10" 
            :step="1" 
            :show-tooltip="true"
            style="width: 120px;" 
            @change="downloadStore.updateMaxConcurrentTasks"
          />
          <span style="font-size: 12px; margin-left: 8px;">{{ downloadStore.maxConcurrentTasks }}</span>
        </div>
        <ElButton size="small" @click="clearCompletedTasks()" v-if="filteredTasks.filter(t => t.status === DownloadStatus.COMPLETED).length > 0">
          清空已完成
        </ElButton>
        <ElButton size="small" type="danger" @click="clearAllTasks()" v-if="filteredTasks.length > 0">
          清空全部
        </ElButton>
      </div>
    </div>
    
    <div class="filter-bar">
      <ElTag 
        v-for="(filter, key) in { 'all': '全部', 'waiting': '等待中', 'downloading': '下载中', 'completed': '已完成', 'failed': '失败', 'paused': '已暂停' }" 
        :key="key"
        :type="filterType === key ? 'primary' : ''"
        @click="filterType = key"
        style="cursor: pointer; margin-right: 8px;"
      >
        {{ filter }}
      </ElTag>
    </div>
    
    <ElTable 
      :data="filteredTasks" 
      size="small" 
      style="width: 100%"
      v-loading="false"
    >
      <ElTableColumn prop="bookname" label="书名" width="200">
        <template #default="scope">
          <div class="book-info">
            <span class="bookname">{{ scope.row.bookname }}</span>
            <span class="author">{{ scope.row.author }}</span>
          </div>
        </template>
      </ElTableColumn>
      
      <ElTableColumn label="进度" width="200">
        <template #default="scope">
          <div class="progress-container">
            <ElProgress 
              :percentage="scope.row.progress" 
              :status="scope.row.status === DownloadStatus.DOWNLOADING ? 'success' : 'exception'"
              :show-text="true"
              text-inside
              stroke-width="12"
            />
          </div>
        </template>
      </ElTableColumn>
      
      <ElTableColumn prop="downloadedChapters" label="进度" width="120">
        <template #default="scope">
          {{ scope.row.downloadedChapters }}/{{ scope.row.totalChapters }}
        </template>
      </ElTableColumn>
      
      <ElTableColumn label="状态" width="100">
        <template #default="scope">
          <ElTag :type="getStatusInfo(scope.row.status).type">
            {{ getStatusInfo(scope.row.status).text }}
          </ElTag>
        </template>
      </ElTableColumn>
      
      <ElTableColumn label="时间" width="180">
        <template #default="scope">
          <div class="time-info">
            <div v-if="scope.row.startTime">
              开始: {{ formatTime(scope.row.startTime) }}
            </div>
            <div v-if="scope.row.endTime">
              结束: {{ formatTime(scope.row.endTime) }}
            </div>
            <div v-if="scope.row.startTime">
              耗时: {{ formatDuration(scope.row.startTime, scope.row.endTime) }}
            </div>
          </div>
        </template>
      </ElTableColumn>
      
      <ElTableColumn label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="actions">
            <ElDropdown>
              <ElButton size="small" :icon="IconMore" class="action-btn" />
              <ElDropdownMenu slot="dropdown">
                <ElDropdownItem v-if="scope.row.status === DownloadStatus.DOWNLOADING" @click="pauseTask(scope.row.id)">
                  <IconPause style="margin-right: 5px;" />
                  暂停
                </ElDropdownItem>
                <ElDropdownItem v-if="scope.row.status === DownloadStatus.WAITING || scope.row.status === DownloadStatus.PAUSED" @click="startTask(scope.row.id)">
                  <IconPlay style="margin-right: 5px;" />
                  开始
                </ElDropdownItem>
                <ElDropdownItem v-if="scope.row.status === DownloadStatus.FAILED" @click="retryTask(scope.row.id)">
                  <IconRedo style="margin-right: 5px;" />
                  重试
                </ElDropdownItem>
                <ElDropdownItem v-if="scope.row.status !== DownloadStatus.DOWNLOADING" @click="cancelTask(scope.row.id)" danger>
                  <IconDelete style="margin-right: 5px;" />
                  删除
                </ElDropdownItem>
              </ElDropdownMenu>
            </ElDropdown>
          </div>
        </template>
      </ElTableColumn>
    </ElTable>
    
    <div v-if="filteredTasks.length === 0" class="empty-tasks">
      <div class="empty-icon">📥</div>
      <p>暂无{{ getFilterText(filterType) }}下载任务</p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.download-tasks {
  width: 800px;
  max-height: 600px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    border-bottom: 1px solid #eee;
    
    h3 {
      margin: 0;
      font-size: 16px;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .filter-bar {
    padding: 10px 20px;
    border-bottom: 1px solid #eee;
  }
  
  .book-info {
    .bookname {
      display: block;
      font-weight: 500;
    }
    .author {
      display: block;
      font-size: 12px;
      color: #666;
      margin-top: 4px;
    }
  }
  
  .progress-container {
    padding: 5px 0;
  }
  
  .time-info {
    font-size: 12px;
    color: #666;
    
    div {
      margin-bottom: 2px;
    }
  }
  
  .actions {
    display: flex;
    justify-content: center;
    
    .action-btn {
      padding: 0;
      width: 32px;
    }
  }
  
  .empty-tasks {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 200px;
    color: #999;
    text-align: center;
    padding: 20px;
  
    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
      opacity: 0.6;
    }
    
    p {
      margin: 0;
      font-size: 14px;
      line-height: 1.5;
    }
  }
}
</style>